<template>
    <div>
        <el-dialog :visible.sync="visible" width="80%" center :before-close="handleClose" append-to-body
            :title="'请选择课件'">
            <el-row>
                <el-form :inline="true" ref="form" :model="form" label-width="66px" class="demo-form-inline" clo>

                    <el-form-item label="" prop="type">
                        <el-select size="mini" v-model="form.is_folder" placeholder="筛选课件展示形式" filterable clearable>
                            <el-option v-for="item in file_types" :key="item.is_folder" :label="item.name"
                                :value="item.is_folder">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="" prop="book_type">
                        <el-select size="mini" v-model="form.book_type" placeholder="筛选课件分类" filterable clearable>
                            <el-option v-for="item in book_types" :key="item.book_type" :label="item.book_name"
                                :value="item.book_type">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="title">
                        <el-input size="mini" placeholder="输入教材/课件名称" v-model="form.title" filterable clearable></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="search" size="mini">筛选</el-button>
                        <span style="color: red;font-size: 20px;" v-if="task_type < 999 ">
                            (鼠标单击选中课件,若为集合类课件,则双击可进入选中具体内容)
                        </span>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <el-row>
                    <div class="content">
                        <div class="content__item" v-for="(item, index) in tableData">
                            <div v-if="item.is_folder == 1">

                                <div>
                                    <p style="position: relative;">
                                        <img src="@/assets/img/kanke/courseware/folder.png" alt="暂无图片"
                                            style="vertical-align: middle;width: 170px; height: 150px;"
                                            @click="folderDetail(item.id)">
                                    </p>
                                    <p style="width: 169px;height: 57px;overflow: hidden;text-overflow:ellipsis;
                               display: -webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;">
                                        {{ item.title }}
                                    </p>
                                </div>

                            </div>
                            <!--  文件 -->
                            <div v-else>
                                <div>
                                    <p></p>
                                    <div style="position: relative;display: inline-block;">
                                        <img :src="item.cover_url" alt="暂无图片"
                                            style="vertical-align: middle;width: 170px; height: 150px;position: relative;"
                                            @click="selectFiles(item)" v-on:dblclick="handleDoubleSelectFile(item)">

                                        <el-alert :title="showType(item.book_type)" type="success"
                                            style="width: 75px;height:22px;top:0;background-color: #00FFFE;text-align: center;color: black;position: absolute;left: 0;"
                                            :closable="false">
                                        </el-alert>

                                        <el-alert v-if="item.is_multiple == 2" title="集合" type="success"
                                            style="width: 75px;height:22px;top:0;background-color: #42b983;text-align: center;color: black;position: absolute;right: 0;"
                                            :closable="false">
                                        </el-alert>
                                        <el-alert v-else title="单一" type="success"
                                            style="width: 75px;height:22px;top:0;background-color: #C8A2C8;text-align: center;color: black;position: absolute;right: 0;"
                                            :closable="false">
                                        </el-alert>

                                        <label class="checkbox-label" :fileId="item.id">
                                            <!--                                            :class="multipleSelectionIdArr.includes(item.id) ? 'checked' : ''">-->
                                            <img src="@/assets/img/kanke/courseware/select.png" alt="暂无图片"
                                                style="width: 30px;height: 30px;">
                                        </label>
                                    </div>
                                    <p style="width: 169px;height: 57px;overflow: hidden;text-overflow:ellipsis;
                               display: -webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;white-space: break-spaces;">
                                        {{ item.title }}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-row>
                <div class="block">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="pageInfo.pageNumber" :page-sizes="pageSizes" :page-size="pageInfo.pageSize"
                        background layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total">
                    </el-pagination>
                </div>
            </el-row>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleClose" size="small">取 消</el-button>
                <el-button type="primary" @click="submitForm('form')" size="small">确 定</el-button>
            </div>
        </el-dialog>

        <div v-if="ShowAddFolderDetailVisible">
          <show-add-folder-detail :visible.sync="ShowAddFolderDetailVisible" :task_type="task_type" :current_day="current_day"
                                  :edit_task_courseware_arr="edit_task_courseware_arr"
                                  :id="form.id">
          </show-add-folder-detail>
        </div>

        <div v-if="ShowAddCoursewareContentVisible">
            <show-add-courseware-content :visible.sync="ShowAddCoursewareContentVisible"
                @HandleCoursewareSelectFile="HandleCoursewareSelectFile"
                :edit_task_courseware_arr="edit_task_courseware_arr" :current_courseware_info="current_courseware_info"
                :current_courseware_id="current_courseware_id"></show-add-courseware-content>
        </div>

    </div>
</template>
<script>
import { pageSizes } from '@/constant/index.js'
import { getList, moveFiles} from "@/api/kanke/textbook/coursewarepub";
import ShowAddFolderDetail from "@/views/kanke/textbook/courseware/components/ShowAddFolderDetail";
import ShowAddCoursewareContent from "./ShowAddCoursewareContent";
export default {
    name: "ShowAddCourseWare",
    components: {
        ShowAddFolderDetail,
        ShowAddCoursewareContent
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        task_type: {
            type: [Number, String],
            default: 0
        },
        edit_task_courseware_arr: {
            type: Array,
            default: () => []
        },
        current_day: {
            type: String,
            default: "taskFirstDay"
        },
    },
    data() {
        return {
            loading: false,
            ShowFolderVisible: false,
            ShowFormFolderVisible: false,
            ShowAddFolderDetailVisible: false,
            ShowAddCoursewareContentVisible: false, //课件中可能包括多个视频等
            showControlButton1: true,
            showControlButton2: false,
            current_courseware_id: 0,  //需要进入选择具体内容的课件id
            current_courseware_info: {},
            need_delete_course_list: [],
            form: {
                book_type: '',
                is_folder: '',
                title: '',
            },
            formFolder: {
                id: 0,
                maxLength: 24,
                title: ''
            },
            pageInfo: {
                pageNumber: 1,
                pageSize: 10,
                total: 0
            },
            file_types: [
                { 'is_folder': 1, 'name': '文件夹' },
                { 'is_folder': 0, 'name': '课件' }
            ],
            book_types: [
                { 'book_type': 1, 'book_name': '课本' },
                { 'book_type': 2, 'book_name': '视频' },
                { 'book_type': 3, 'book_name': 'PPT' },
                { 'book_type': 4, 'book_name': '音频' },
            ],
            multipleSelection: [],  //多选内容
            multipleSelectionIdArr: [],  //多选id

            tableData: [],
            type: 'book',
            pageSizes
        }
    },
    computed: {
        tmpTaskData() {
            return this.$store.state.assignTask.tmpTaskData;
        }
    },
    watch: {
    },
    created() {
        this.init(true);
    },
    mounted() {
        console.log('添加课件弹出显示当前天',this.current_day);
        this.$store.commit('RESET_TMP_TASK_DATA');
        if (this.edit_task_courseware_arr.length > 0) {
            for (let i = 0; i < this.edit_task_courseware_arr.length; i++) {
                this.$store.commit('SET_TMP_TASK_DATA', this.edit_task_courseware_arr[i]);
            }
        }
    },
    updated() {
        this.initSelectedFiles();
    },
    methods: {
        async init(initation = false) {

            const params = {
                ...this.form,
                ...this.pageInfo
            };
            this.loading = true;

            await getList(params).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data.data
                    this.pageInfo.total = res.data.total
                }
                this.loading = false
            })
        },

        //初始化选中的数据 选中状态
        initSelectedFiles() {
            let labelCheck = document.getElementsByClassName('checkbox-label');
            //重置
            for (let j = 0; j < labelCheck.length; j++) {
                labelCheck[j].style.display = "none";
            }
            if (this.tmpTaskData.length > 0) {
                for (let i = 0; i < this.tmpTaskData.length; i++) {
                    for (let j = 0; j < labelCheck.length; j++) {
                        if (this.tmpTaskData[i].id == labelCheck[j].getAttribute('fileId')) {
                            labelCheck[j].style.display = "block";
                            break;
                        }
                    }
                }

            }
        },

        handleDoubleSelectFile(obj) {
            console.log('handleDoubleSelectFile log', obj);
            if (obj.is_multiple != 2) {
                return;
                this.msgError("非集合类课件,只能单击选中");
            }
            let book_type = 0;
            switch (this.task_type) {
                case 1:
                    book_type = 4;
                    break;
                case 2:
                    book_type = 2;
                    break;
                case 3:
                    book_type = 3;
                    break;
                case 4:
                    book_type = 0;  //创作类型
                    break;
                default:
                    break;
            }

          if (book_type > 0) {
            if (book_type != obj.book_type || obj.book_type == 1) {
                return;
            }
          }
          this.current_courseware_id = obj.id;
          this.current_courseware_info = obj
          this.ShowAddCoursewareContentVisible = true;
        },

        //处理合集类选择内容相关数据
        HandleCoursewareSelectFile(data) {
            console.log('---选择课件内容---', data);
            this.$store.commit('SET_TMP_TASK_DATA', data);
            this.initSelectedFiles();
        },
        search() {
            this.pageInfo.pageNumber = 1;
            this.init();
        },
        folderDetail(id) {
            this.form.id = id;
            this.ShowAddFolderDetailVisible = true
        },
        //单击选择文件
        selectFiles(obj) {
            console.log('click selected file', obj);
            let book_type = 0; //创作类型
            switch (this.task_type) {
                case 1:
                    book_type = 4;      //听力
                    break;
                case 2:
                    book_type = 2;      //阅读
                    break;
                case 3:
                    book_type = 3;      //录音
                    break;
                case 4:
                    break;
                default:
                    break;
            }
            if (book_type > 0) {
                if ((book_type && book_type != obj.book_type) || obj.book_type == 1) {
                    this.msgError("当前类型与所选课件类型不一致");
                    return;
                }
            }
            if(obj.book_type == 1 && this.task_type == 4){
              this.msgError("创作类型不能添加课本");
              return;
            }
            //任务模板列表进入 需要选择课件内容 只能双击
            if ((book_type == 4 || book_type == 2) && obj.is_multiple == 2) {
                this.msgError("该课件包含多个内容，请双击选中具体某个内容");
                return;
            }

            //判断是选中还是取消选中
            let is_exist = 0;
            for (let i = 0; i < this.tmpTaskData.length; i++) {
                if (this.tmpTaskData[i].id == obj.id && this.tmpTaskData[i].content_id == obj.content_id) {
                    //删除课件
                    is_exist = 1;
                    this.$store.commit('DELETE_TMP_TASK_DATA', { id: obj.id, content_id: obj.content_id });
                    break;
                }
            }
            //若不存在该课件 则添加该课件
            if (is_exist == 0) {
                this.$store.commit('SET_TMP_TASK_DATA', obj);
            }
            console.log('----now tmp data', this.tmpTaskData);

            this.initSelectedFiles();
        },
        showType(book_type) {
            for (let i = 0; i < this.book_types.length; i++) {
                if (book_type == this.book_types[i].book_type) {
                    return this.book_types[i].book_name;
                }
            }
        },
        handleClose() {
            this.$emit('update:visible', false);
        },
        submitForm() {
            //判断是否为布置任务选择
            console.log('---edit task day--', this.tmpTaskData);

            //添加排序值 start
            if(this.tmpTaskData.length >0){
                this.$store.commit("GET_TASK_MAX_SORT",{'current_day':this.current_day})
                console.log('获取当前最大排序值',this.$store.state.assignTask.max_sort);
                let max_sort = this.$store.state.assignTask.max_sort;
                for(let i=0;i<this.tmpTaskData.length;i++){
                    this.tmpTaskData[i].sort = max_sort + i + 1;
                }
            }
            //添加排序值 end


            this.$emit('handleSelectFiles', this.tmpTaskData);
            this.$emit('update:visible', false);
            this.multipleSelection = [];

        },
       removeDuplicateElements(arr) {

          const seen = new Set();
          const result = [];
          for (const item of arr) {
              const key = item.id + '@' + item.content_id;
              if (!seen.has(key)) {
                  seen.add(key);
                  result.push(item);
              }
          }
          return result;
        },
        handleSizeChange(val) {
            this.pageInfo.pageSize = val
            this.init()
        },
        handleCurrentChange(val) {
            this.pageInfo.pageNumber = val
            this.init()
        }
    }
}
</script>
<style lang="scss" scoped>
.demo-form-inline {
    ::v-deep .el-select .el-input {
        width: 150px;
    }
}

::v-deep .el-alert {
    border-radius: 0;
}

.checkbox-label {
    position: absolute;
    top: 0;
    right: 0;
    display: none;
}

.checkbox-label.checked {
    display: block;
}

::v-deep .el-dialog__header {
    background: #03A7EF;
}

.content {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    justify-content: flex-start;
    margin-bottom: 15px;
    min-height: 450px;

    &__item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin: 20px;

        .title {
            margin-top: 10px;
        }
    }
}
</style>